package com.xiaohai.controller;

import com.xiaohai.common.R;
import com.xiaohai.exception.CustomException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * ClassName:CommonController
 * Package:IntelliJ IDEA
 * Description:
 * Author 何诗海
 *
 * @Create 2024/1/16 14:03
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${file.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
            log.info("文件创建成功，文件的路径为:{}", dir.getAbsolutePath());
        }
        File imagesFile = new File(dir + "\\/\\" + fileName);
        log.info(imagesFile.getAbsolutePath());

        try {
            file.transferTo(imagesFile);
        } catch (IOException e) {
            throw new CustomException("文件上传失败");
        }
        return R.success("上传成功,路径：127.0.0.1:80/images/" + fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        File imagesFile = new File(path + "\\/\\" + name);
        response.setContentType("image/jpeg");
        try (FileInputStream inputStream = new FileInputStream(imagesFile);
             ServletOutputStream outputStream = response.getOutputStream();) {
            byte[] bytes = new byte[1204];
            int length = 0;
            while ((length = inputStream.read()) != -1) {
                outputStream.write(bytes, 0, length);
            }
        } catch (Exception e) {
            throw new CustomException("文件下载失败！");
        }

    }
}
